﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace _443_Server
{
	public class ClientRequest
	{
		private static int[] updateKeys = {
			-1, 0, -1, 0, 0, 0, 0, 56, 41,
			-50, -17, 97, 53, 48, 105, -13, -32, 7, -50, -22, 45, 120, -117,
			-44, -126, 13, 2, -30, -117, 90, 104, 38, 69, 89, 34, -37, 109,
			-95, -80, 36, 23, -53, 5, -65, 5, -30, 113, -58, 46, -53, -92, -83,
			-45, 62, 52, 73, -112, 79, 79, -87, 107, 119, 56, 51
		};

		public static void ForfillRequest(NetworkStream nin, NetworkStream nout)
		{
			try
			{
				int revision = (nin.ReadByte() << 24) + (nin.ReadByte() << 16) + (nin.ReadByte() << 8) + nin.ReadByte();
				if (revision != 443)
				{
					Console.WriteLine("[Thread " + Thread.CurrentThread.ManagedThreadId + "] Connection from client returned revision " + revision + ".");
					return;
				}

				nout.WriteByte(0);
				int packetSize = nin.ReadByte();
				if (packetSize + 4 == 7)
				{
					for (int i = 0; i < packetSize; i++)
						nin.ReadByte();
					foreach (int i in updateKeys)
						nout.WriteByte((byte)i);
					for (int i = 0; i < 4; i++)
						nin.ReadByte();
				}
			}
			catch (Exception)
			{
				Console.WriteLine("[Thread " + Thread.CurrentThread.ManagedThreadId + "] Connection from client exception.");
			}
			finally
			{
				try
				{
					nin.Close();
					nout.Close();
				}
				catch (Exception)
				{
				}
				finally
				{
					nin = null;
					nout = null;
				}
			}
		}
	}
}
